# -*- coding: utf-8 -*-
import logging
import os
import time
import requests
from pyquery import PyQuery
from scrapy.utils.project import get_project_settings
from zc_core.plugins.verify_code import VerifyCode

logger = logging.getLogger('login')


class Captcha(object):

    def __init__(self, timeout=60):
        settings = get_project_settings()
        self.max_login_retry = settings.get('MAX_LOGIN_RETRY', 2)

    def store_goods_regist(self):
        settings = get_project_settings()
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/6.2.4094.1 Safari/537.36',
        }
        seesion = requests.session()
        page = seesion.get('http://120.35.30.176/shopping/goodslist.htm?store_id=2c9be59563015d04016304d397df0561',
                           headers=headers)
        if page and page.status_code == 200:
            jpy = PyQuery(page.text)
            # token
            token = jpy('meta[name="csrf-token"]').attr('content')

            # 验证码结果
            catpcha = seesion.get('http://120.35.30.176/shopping/getCatpcha.htm', headers=headers)
            """图片路径"""
            base_path = os.path.join(settings.get('OUTPUT_ROOT'), 'verify_code\\')
            if not os.path.exists(base_path):
                os.makedirs(base_path)
            file = os.path.join(base_path, '%s.png' % str(time.strftime('%Y%m%d%H%M%S')))
            """图片保存"""
            with open(file, 'wb') as f:
                f.write(catpcha.content)
            """识别结果"""
            code = VerifyCode().verify(file, code_type='6001')

            # 提交认证
            if token and code is not None:
                regist = seesion.post(
                    'http://120.35.30.176/shopping/regisCatpcha.htm',
                    headers=headers,
                    data={
                        'captchaCode': code,
                        'identifyType': 'goodslist.htm',
                        'store_id': '2c9be59563015d04016304d397df0561',
                        'xToken': token,
                    }
                )
                if regist and regist.status_code == 200:
                    return {
                        'cookie': {
                            'JSESSIONID': seesion.cookies['JSESSIONID']
                        },
                        'xtoken': token
                    }

    def order_list_regist(self):
        settings = get_project_settings()
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3741.400 QQBrowser/10.5.3863.400',
        }
        seesion = requests.session()
        page = seesion.get('http://120.35.30.176/shopping/contractlist.htm', headers=headers)
        if page and page.status_code == 200:
            jpy = PyQuery(page.text)
            # token
            token = jpy('meta[name="csrf-token"]').attr('content')

            # 验证码结果
            catpcha = seesion.get('http://120.35.30.176/shopping/getCatpcha.htm', headers=headers)
            """图片路径"""
            base_path = os.path.join(settings.get('OUTPUT_ROOT'), 'verify_code\\')
            if not os.path.exists(base_path):
                os.makedirs(base_path)
            file = os.path.join(base_path, '%s.png' % str(time.strftime('%Y%m%d%H%M%S')))
            """图片保存"""
            with open(file, 'wb') as f:
                f.write(catpcha.content)
            """识别结果"""
            code = VerifyCode().verify(file, code_type='6001')

            # 提交认证
            if token and code is not None:
                regist = seesion.post(
                    'http://120.35.30.176/shopping/regisCatpcha.htm',
                    headers=headers,
                    data={
                        'captchaCode': code,
                        'identifyType': 'contractlist.htm',
                        'xToken': token,
                    }
                )
                if regist and regist.status_code == 200:
                    return {
                        'cookie': {
                            'JSESSIONID': seesion.cookies['JSESSIONID']
                        },
                        'xtoken': token
                    }


if __name__ == '__main__':
    xtoken = Captcha()
    xtoken.store_goods_regist()
